import { defineStore } from 'pinia'
import { v4 as uuidv4 } from 'uuid'
import { ref } from 'vue'
import type { PersistenceOptions } from 'pinia-plugin-persistedstate'
import { useUserStore } from './user';

type MessageType = {
  type: 'user' | 'ai';
  content: string;
} & (
    | {
      hasThinking: true;
      thinking: {
        content: string;
        done: boolean;
        time: number;
        startTime?: number;
      };
      hasReferences?: boolean;
      references?: any[];
      referenceCount?: number;
    }
    | {
      hasThinking?: false;
      thinking?: undefined;
      hasReferences?: boolean;
      references?: any[];
      referenceCount?: number;
    }
  );

type ChatSession = {
  id: string;
  messages: MessageType[];
  lastUpdateTime: number;
};

type ConnectionState = {
  socket: WebSocket | null;
  isAssistantConnected: boolean;
  isSearchConnected: boolean;
  assistantSessionId: string;
  searchSessionId: string;
  assistantMessage: string;
  searchMessage: string;
  assistantLoading: boolean;
  searchLoading: boolean;
  references: FileReference[];
  error: string;
};

type FileReference = {
  fileName: string
  type: 'code' | 'document' | 'image'
  content: string
}

const WS_BASE_URL = import.meta.env.VITE_WS_BASE_URL;
const ASSISTANT_API_URL = import.meta.env.VITE_ASSISTANT_API_URL;
const SEARCH_API_URL = import.meta.env.VITE_SEARCH_API_URL;
const DIFY_API_KEY = 'app-zfSg9FueN3i8dwwtbaGeD8vK';
const DIFY_API_URL = import.meta.env.VITE_DIFY_API_URL;

export const useChatStore = defineStore(
  'chat',
  () => {
    const assistantSessions = ref<Record<string, ChatSession>>({});
    const aiSearchSessions = ref<Record<string, ChatSession>>({});

    const currentAssistantSessionId = ref<string>('');
    const currentSearchSessionId = ref<string>('');

    const connectionState = ref<ConnectionState>({
      socket: null,
      isAssistantConnected: false,
      isSearchConnected: false,
      assistantSessionId: '',
      searchSessionId: '',
      assistantMessage: '',
      searchMessage: '',
      assistantLoading: false,
      searchLoading: false,
      references: [],
      error: ''
    });

    const difyConnectionState = ref<ConnectionState>({
      socket: null,
      isAssistantConnected: false,
      isSearchConnected: false,
      assistantSessionId: '',
      searchSessionId: '',
      assistantMessage: '',
      searchMessage: '',
      assistantLoading: false,
      searchLoading: false,
      error: '',
      references: []
    });

    const generateSessionId = (): string => {
      return uuidv4();
    };

    const getCurrentAssistantMessages = () => {
      if (!currentAssistantSessionId.value || !assistantSessions.value[currentAssistantSessionId.value]) {
        return [];
      }
      return assistantSessions.value[currentAssistantSessionId.value].messages;
    };

    const getCurrentSearchMessages = () => {
      if (!currentSearchSessionId.value || !aiSearchSessions.value[currentSearchSessionId.value]) {
        return [];
      }
      return aiSearchSessions.value[currentSearchSessionId.value].messages;
    };

    const saveAssistantMessages = (sessionId: string, messages: MessageType[]) => {
      assistantSessions.value[sessionId] = {
        id: sessionId,
        messages: [...messages],
        lastUpdateTime: Date.now()
      };
      currentAssistantSessionId.value = sessionId;
    };

    const saveSearchMessages = (sessionId: string, messages: MessageType[]) => {
      aiSearchSessions.value[sessionId] = {
        id: sessionId,
        messages: [...messages],
        lastUpdateTime: Date.now()
      };
      currentSearchSessionId.value = sessionId;
    };

    const clearAssistantMessages = (sessionId: string) => {
      if (assistantSessions.value[sessionId]) {
        delete assistantSessions.value[sessionId];
      }
      if (currentAssistantSessionId.value === sessionId) {
        currentAssistantSessionId.value = '';
      }
    };

    const clearSearchMessages = (sessionId: string) => {
      if (aiSearchSessions.value[sessionId]) {
        delete aiSearchSessions.value[sessionId];
      }
      if (currentSearchSessionId.value === sessionId) {
        currentSearchSessionId.value = '';
      }
    };

    const clearAllSessions = () => {
      assistantSessions.value = {};
      aiSearchSessions.value = {};
      currentAssistantSessionId.value = '';
      currentSearchSessionId.value = '';
    };

    const getAssistantSessionList = () => {
      return Object.values(assistantSessions.value).sort((a, b) => b.lastUpdateTime - a.lastUpdateTime);
    };

    const getSearchSessionList = () => {
      return Object.values(aiSearchSessions.value).sort((a, b) => b.lastUpdateTime - a.lastUpdateTime);
    };

    const connectWebSocket = (sessionId: string, type: 'assistant' | 'search') => {
      closeWebSocket();

      const wsUrl = `${WS_BASE_URL}/${sessionId}`;
      console.log('连接WebSocket:', wsUrl);

      try {
        const socket = new WebSocket(wsUrl);
        connectionState.value.socket = socket;

        socket.onopen = () => {
          console.log(`${type} WebSocket已连接`);
          if (type === 'assistant') {
            connectionState.value.isAssistantConnected = true;
            connectionState.value.assistantSessionId = sessionId;
          } else {
            connectionState.value.isSearchConnected = true;
            connectionState.value.searchSessionId = sessionId;
          }
        };

        socket.onmessage = (event) => {
          const data = event.data;
          handleIncomingMessage(data, type);
        };

        socket.onerror = (event) => {
          console.error('WebSocket错误:', event);
          connectionState.value.error = 'WebSocket连接出错';
          if (type === 'assistant') {
            connectionState.value.assistantLoading = false;
          } else {
            connectionState.value.searchLoading = false;
          }
        };

        socket.onclose = () => {
          console.log(`${type} WebSocket连接已关闭`);
          if (type === 'assistant') {
            connectionState.value.isAssistantConnected = false;
          } else {
            connectionState.value.isSearchConnected = false;
          }
        };

        return true;
      } catch (err) {
        console.error('创建WebSocket失败:', err);
        connectionState.value.error = `创建WebSocket失败: ${err instanceof Error ? err.message : String(err)}`;
        return false;
      }
    };

    const handleIncomingMessage = (data: string, type: 'assistant' | 'search') => {
      if (data && data.trim() === 'END') {
        if (type === 'assistant') {
          connectionState.value.assistantLoading = false;
          console.log('AI助教完整消息内容:', connectionState.value.assistantMessage);
        } else {
          connectionState.value.searchLoading = false;
          console.log('AI搜索完整消息内容:', connectionState.value.searchMessage);
        }
        return;
      }

      try {
        const cleanData = data.replace(/^START\s*/g, '');
        if (type === 'assistant') {
          connectionState.value.assistantMessage += cleanData;
        } else {
          connectionState.value.searchMessage += cleanData;
        }
      } catch (e) {
        console.error('处理消息异常:', e);
        if (data.trim()) {
          if (type === 'assistant') {
            connectionState.value.assistantMessage += data.trim();
          } else {
            connectionState.value.searchMessage += data.trim();
          }
        }
      }
    };

    const closeWebSocket = () => {
      if (connectionState.value.socket) {
        try {
          connectionState.value.socket.close();
          console.log('WebSocket连接已关闭');
        } catch (error) {
          console.error('关闭WebSocket时出错:', error);
        }
      }
      connectionState.value.socket = null;
      connectionState.value.isAssistantConnected = false;
      connectionState.value.isSearchConnected = false;
    };

    const stopStream = (type: 'assistant' | 'search') => {
      if (type === 'assistant') {
        console.log('中断AI助教消息:', connectionState.value.assistantMessage);
        connectionState.value.assistantLoading = false;
      } else {
        console.log('中断AI搜索消息:', connectionState.value.searchMessage);
        connectionState.value.searchLoading = false;
      }
      closeWebSocket();
    };

    const sendAssistantMessage = async (sessionId: string, messageText: string) => {
      if (!messageText.trim()) {
        connectionState.value.error = '消息不能为空';
        return;
      }

      connectionState.value.assistantLoading = true;
      connectionState.value.assistantMessage = '';

      try {
        const wsConnected = connectWebSocket(sessionId, 'assistant');
        if (!wsConnected) {
          throw new Error('WebSocket连接失败');
        }

        console.log('发送AI助教POST请求到:', ASSISTANT_API_URL);
        const response = await fetch(ASSISTANT_API_URL, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            sessionId: sessionId,
            message: messageText,
            type: 'assistant'
          })
        });

        if (!response.ok) {
          throw new Error(`HTTP错误: ${response.status}`);
        }
      } catch (err) {
        console.error('发送AI助教消息失败:', err);
        connectionState.value.error = `发送消息失败: ${err instanceof Error ? err.message : String(err)}`;
        connectionState.value.assistantLoading = false;
        closeWebSocket();
      }
    };
    const sendDifyMessage = async (sessionId: string, messageText: string) => {
      if (!messageText.trim()) {
        connectionState.value.error = '消息不能为空';
        return;
      }

      connectionState.value.assistantLoading = true;
      connectionState.value.assistantMessage = '';

      try {
        // const wsConnected = connectWebSocket(sessionId, 'assistant');
        // if (!wsConnected) {
        //   throw new Error('WebSocket连接失败');
        // }

        console.log('发送AI助教POST请求到:', DIFY_API_URL);
        const response = await fetch(`${DIFY_API_URL}/chat-messages`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${DIFY_API_KEY}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            conversation_id: "",
            inputs: {},
            query: messageText,
            response_mode: 'streaming',
            user: useUserStore().user.id ? useUserStore().user.id : '1234567890',
          }),
        })

        if (!response.ok) {
          throw new Error(`HTTP错误: ${response.status}`);
        }

        const reader = response.body?.getReader()
        let assistantMessage = ''
        let references: FileReference[] = []
        while (reader) {
          const { done, value } = await reader.read()
          if (done) break
    
          const chunk = new TextDecoder().decode(value)
          const lines = chunk.split('\n').filter(line => line.trim())
    
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const data = JSON.parse(line.slice(5))
                if (data.event === 'message') {
                  assistantMessage += data.answer
                  // 更新最后一条消息
                  connectionState.value.assistantMessage = assistantMessage
                } else if (data.event === 'message_end') {
                  connectionState.value.assistantSessionId = data.conversation_id
                  // 处理文件引用（这里使用示例数据，实际应该从 API 响应中获取）
                  if (data.metadata) {
                    // references = data.metadata.retriever_resources
                    const retriever_resources = data.metadata.retriever_resources   
                    references = retriever_resources.map((resource: any) => ({
                      fileName: resource.document_name,
                      type: resource.data_source_type,
                      content: resource.content
                    }))
                  }
                }
                // 完成思考，更新消息
                connectionState.value.assistantLoading = false
                connectionState.value.references = references
              } catch (e) {
                console.error('解析响应数据失败:', e)
              }
            }
          }
        }
      } catch (err) {
        console.error('发送AI助教消息失败:', err);
        connectionState.value.error = `发送消息失败: ${err instanceof Error ? err.message : String(err)}`;
        connectionState.value.assistantLoading = false;
        // closeWebSocket();
      }
    };

    const sendSearchMessage = async (sessionId: string, messageText: string) => {
      if (!messageText.trim()) {
        connectionState.value.error = '消息不能为空';
        return;
      }

      connectionState.value.searchLoading = true;
      connectionState.value.searchMessage = '';

      try {
        const wsConnected = connectWebSocket(sessionId, 'search');
        if (!wsConnected) {
          throw new Error('WebSocket连接失败');
        }

        console.log('发送AI搜索POST请求到:', SEARCH_API_URL);
        const response = await fetch(SEARCH_API_URL, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            sessionId: sessionId,
            message: messageText
          })
        });

        if (!response.ok) {
          throw new Error(`HTTP错误: ${response.status}`);
        }
      } catch (err) {
        console.error('发送AI搜索消息失败:', err);
        connectionState.value.error = `发送消息失败: ${err instanceof Error ? err.message : String(err)}`;
        connectionState.value.searchLoading = false;
        closeWebSocket();
      }
    };

    const clearAssistantMessage = () => {
      connectionState.value.assistantMessage = '';
    };

    const clearSearchMessage = () => {
      connectionState.value.searchMessage = '';
    };

    return {
      assistantSessions,
      aiSearchSessions,
      currentAssistantSessionId,
      currentSearchSessionId,
      connectionState,
      difyConnectionState,

      generateSessionId,
      getCurrentAssistantMessages,
      getCurrentSearchMessages,
      saveAssistantMessages,
      saveSearchMessages,
      clearAssistantMessages,
      clearSearchMessages,
      clearAllSessions,
      getAssistantSessionList,
      getSearchSessionList,

      sendAssistantMessage,
      sendDifyMessage,
      sendSearchMessage,
      stopStream,
      closeWebSocket,
      clearAssistantMessage,
      clearSearchMessage
    };
  },
  {
    persist: {
      key: 'witdata-chat-store',
      storage: localStorage,
      paths: ['assistantSessions', 'aiSearchSessions', 'currentAssistantSessionId', 'currentSearchSessionId'],
    } as PersistenceOptions
  }
);
